package com.monkeybrother.thread.atomic;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;

/**
 * @Desc
 * @Author houry
 * @Date 2021/2/3 9:23
 **/
public class ThreadPoolTest {
    static ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 10, 0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>(1),
            new UnvSocketThreadFactory("unv-serverSocket-threadPool"),
            new ThreadPoolExecutor.DiscardPolicy());

    /**
     * 对接-宇视面板机器-自定义线程工厂
     */
    static class UnvSocketThreadFactory implements ThreadFactory {
        /**
         * 线程池数量
         */
        private final AtomicInteger poolNumber = new AtomicInteger(1);
        /**
         * 线程组
         */
        private final ThreadGroup threadGroup;
        /**
         * 线程数量
         */
        private final AtomicInteger threadNumber = new AtomicInteger(1);
        /**
         * 线程名前缀
         */
        public final String namePrefix;

        public UnvSocketThreadFactory(String name) {
            SecurityManager s = System.getSecurityManager();
            threadGroup = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
            if (null == name || "".equals(name.trim())) name = "pool";
            namePrefix = name + "-" + poolNumber.getAndIncrement() + "-unv-thread-";
        }

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(threadGroup, r, namePrefix + threadNumber.getAndIncrement(), 0);
            if (t.isDaemon()) t.setDaemon(false);
            if (t.getPriority() != Thread.NORM_PRIORITY) t.setPriority(Thread.NORM_PRIORITY);
            return t;
        }
    }


    public static void main(String[] args) {
        new Thread(() ->{
           while (true) {
               executor.submit(() -> {
                   System.out.println(Thread.currentThread().getName() + "：test");
               });
           }
        }).start();


    }
}
